package com.huanbao.nongwu.controller;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageInfo;
import com.huanbao.common.api.CommonResult;
import com.huanbao.common.exception.BusinessException;
import com.huanbao.common.exception.GateWayException;
import com.huanbao.common.pojo.nwrabc.SysRole;
import com.huanbao.common.pojo.nwrabc.SysUser;
import com.huanbao.common.pojo.nwrabc.SysUserRole;
import com.huanbao.nongwu.controller.base.BaseWebController;
import com.huanbao.nongwu.pojo.SysUserVO;
import com.huanbao.nongwu.service.SysUserRoleServiceImpl;
import com.huanbao.nongwu.service.SysUserServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/* ━━━━━━佛祖保佑━━━━━━
 *                  ,;,,;
 *                ,;;'(    社
 *      __      ,;;' ' \   会
 *   /'  '\'~~'~' \ /'\.)  主
 * ,;(      )    /  |.     义
 *,;' \    /-.,,(   ) \    码
 *     ) /       ) / )|    农
 *     ||        ||  \)
 *     (_\       (_\
 * ━━━━━━永无BUG━━━━━━
 * @author ：zjq
 * @date ：2021/3/24 10:05
 * @description: TODO
 * @version: V1.0
 * @slogan: 天下风云出我辈，一入代码岁月催
 */
@RestController
@RequestMapping("users")
public class SysUserController extends BaseWebController {

    @Autowired
    private SysUserServiceImpl iSysUserService;

    @Autowired
    private SysUserRoleServiceImpl iSysUserRoleService;


    /**
     * 查询用户列表
     *
     * @throws IOException
     */
    @RequestMapping("/getuserdata")
    public CommonResult getuserdata(String pageNum, String pageSize) {
        Map<String, Object> map = new HashMap();
        map.put("pageNum", pageNum);
        map.put("pageSize", pageSize);
        PageInfo<SysUserVO> p = iSysUserService.getAllUserWithRoleName(map);
        return CommonResult.success(p);
    }


    /**
     * 新增 用户
     *
     * @return
     */
    @RequestMapping("/addnewusers")
    public CommonResult addnewusers(@RequestBody SysUserVO sysUserVO) throws BusinessException {
        SysUser sysUser = new SysUser();
        sysUser.setDepartment(sysUserVO.getDepartment());
        //初始密码与登录名一致
        sysUser.setLoginpwd(sysUserVO.getLoginusername());
        sysUser.setLoginname(sysUserVO.getLoginusername());
        sysUser.setTelephone(sysUserVO.getTelephone());
        sysUser.setUseremail(sysUserVO.getUseremail());
        sysUser.setUsername(sysUserVO.getUsername());


        SysUser u = iSysUserService.checkUserByLoginName(sysUser.getLoginname());
        if (null != u) {
            throw new BusinessException("该用户已存在");
        }

        //以上是封装对象封装代码
        int userCount = iSysUserService.insert(sysUser);

        if (userCount != 1) {
            throw new BusinessException("插入用户发生错误");
        }

        int roleid = sysUserVO.getRoleid();

        SysUserRole sysUserRole = new SysUserRole();
        sysUserRole.setRoleid(roleid);
        sysUserRole.setUserid(sysUser.getId());

        int roleCount = iSysUserRoleService.insert(sysUserRole);
        if (roleCount != 1) {
            throw new BusinessException("插入用户角色发生错误！");
        }

        return CommonResult.success();
    }


    /**
     * 删除 用户
     */
    @RequestMapping("/deleteselectedusers")
    public CommonResult deleteSelectedUsers(@RequestBody SysUserVO sysUserVO) {
        List<Integer> ids = sysUserVO.getSelectIds();
        for (int i = 0; i < ids.size(); i++) {
            //在这里删除用户 在sysuser表中删除用户
            int deleteUserCount = iSysUserService.deleteByPrimaryKey(ids.get(i));
            //在sysuserrole表中 删除用户
            int deleteUserRoleCount = iSysUserRoleService.deleteUserRoleByUserId(ids.get(i));
            if (deleteUserCount != 1 && deleteUserRoleCount != 1) {
                throw new BusinessException("删除用户失败");
            }
        }
        return CommonResult.success();
    }

    /**
     * 修改 用户
     */
    @RequestMapping("/updateUser")
    public CommonResult updateUser(@RequestBody SysUserVO sysUserVO) {

        SysUser sysUser = new SysUser();

        BeanUtils.copyProperties(sysUserVO, sysUser);

        //更新用户信息
        int count = iSysUserService.updateByPrimaryKeySelective(sysUser);

        //删除原来的用户角色信息
        int deleteUserRoleCount = iSysUserRoleService.deleteUserRoleByUserId(sysUser.getId());

        //更新用户信息
        SysUserRole sysUserRole = new SysUserRole();
        sysUserRole.setRoleid(sysUserVO.getRoleid());
        sysUserRole.setUserid(sysUser.getId());
        int insertUserRoleCount = iSysUserRoleService.insert(sysUserRole);

        if (count == 0 || deleteUserRoleCount == 0 || insertUserRoleCount == 0) {
            throw new BusinessException("更新用户失败");
        }

        return CommonResult.success();
    }

    /**
     * 基本信息 修改 用户
     *
     * @param sysUserVO
     * @throws Exception
     */
    @RequestMapping("/updateuserinfo")
    public CommonResult updateUserInfo(@RequestBody SysUser user)  {

        //根据用户名获取用户id，用户查询
        SysUser sysUser = iSysUserService.getUserByLoginName(user.getLoginname());
        user.setId(sysUser.getId());
        int count = iSysUserService.updateByPrimaryKeySelective(user);
        if (count != 1) {
            throw new BusinessException("更新用戶信息錯誤");
        }
        return CommonResult.success();

    }


}
